﻿using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Xml.Linq;
//
using PerceptiveMCAPI.Types.Internal;
//
namespace PerceptiveMCAPI.Types
{
   public class campaignEcommOrdersOutput : Api_BaseOutput
   {
      public List<campaignEcommOrdersResults> result { get; set; }
      public campaignEcommOrdersParms inputParms { get; private set; }
      // --------------------------------------------------------
      public campaignEcommOrdersOutput( campaignEcommOrdersInput input )
         : base( input )
      {
         result = new List<campaignEcommOrdersResults>();
         inputParms = input.parms;
      }
      // --------------------------------------------------- tostring
      public override string ToString()
      {
         return string.Format( "Orders count: {0}", this.result.Count );
      }

      #region ================================================================== format setup

      // ---- serial
      internal void Format( string api_Request, string api_Response )
      {
         this.api_Request = api_Request;
         this.api_Response = api_Response;
         // ----------------------------------
         if ( this.api_OutputType == EnumValues.OutputType.JSON )
            outputJSON();
         else if ( this.api_OutputType == EnumValues.OutputType.XML )
            outputXML();
      }

      // ---- xmlrpc
      internal void Format( x_campaignEcommOrders[] rpcResult )
      {
         this.api_Request = EnumValues.NotSupplied;
         this.api_Response = EnumValues.NotSupplied;
         // ------------------------
         this.result = FormatResults( rpcResult );
      }

      #endregion

      #region ================================================================= Output

      // ---------------------------------------------------------- outputXML
      private void outputXML()
      {
         XElement xml = XElement.Parse( this.api_Response );
         // error check
         Api_Error error = apiSerial.GetXmlOutputError( xml );
         if ( error != null )
         {
            this.api_ErrorMessages.Add( error );
            return;
         }
         // -------------------------------------------- get values
         try
         {
            int it; DateTime dt; double dbl;
            IEnumerable<XElement> xmlOrders = xml.Elements( "struct" );
            foreach ( XElement ordElem in xmlOrders )
            {
               campaignEcommOrdersResults order = new campaignEcommOrdersResults();
               order.store_id = ordElem.Element( "store_id" ).Value;
               order.store_name = ordElem.Element( "store_name" ).Value;
               order.order_id = ordElem.Element( "order_id" ).Value;
               order.email = ordElem.Element( "email" ).Value;
               double.TryParse( ordElem.Element( "order_total" ).Value, out dbl );
               order.total = dbl;
               double.TryParse( ordElem.Element( "tax_total" ).Value, out dbl );
               order.tax = dbl;
               double.TryParse( ordElem.Element( "ship_total" ).Value, out dbl );
               order.shipping = dbl;
               DateTime.TryParse( ordElem.Element( "order_date" ).Value, out dt );
               order.order_date = dt;
               if ( ordElem.Element( "lines" ).HasElements )
               {
                  IEnumerable<XElement> ordLines = ordElem.Element( "lines" ).Descendants( "struct" );
                  foreach ( XElement line in ordLines )
                  {
                     campaignEcommOrders_item item = new campaignEcommOrders_item();
                     //
                     int.TryParse( line.Element( "line_num" ).Value, out it );
                     item.line_num = it;
                     int.TryParse( line.Element( "product_id" ).Value, out it );
                     item.product_id = it;
                     item.product_name = line.Element( "product_name" ).Value;
                     item.product_sku = line.Element( "product_sku" ).Value;
                     int.TryParse( line.Element( "product_category_id" ).Value, out it );
                     item.category_id = it;
                     item.category_name = line.Element( "product_category_name" ).Value;
                     int.TryParse( line.Element( "qty" ).Value, out it );
                     item.qty = it;
                     double.TryParse( line.Element( "cost" ).Value, out dbl );
                     item.cost = dbl;
                     order.items.Add( item );
                  }
               }
               this.result.Add( order );
            }
         }
         catch ( Exception ex )
         {
            this.api_ErrorMessages.Add( apiException.FormatError( ex ) );
         }
      }

      // ---------------------------------------------------------- outputJSON
      private void outputJSON()
      {
         JavaScriptSerializer jss = new JavaScriptSerializer();

         try
         {
            if ( this.api_Response.Contains( EnumValues.JSONErrorString ) )
            {
               Api_Error err = jss.Deserialize<Api_Error>( this.api_Response );
               this.api_ErrorMessages.Add( err );
            }
            else
            {
               x_campaignEcommOrders[] jsonResult = jss.Deserialize<x_campaignEcommOrders[]>( this.api_Response );
               this.result = FormatResults( jsonResult );
            }
         }
         catch ( Exception ex )
         {
            this.api_ErrorMessages.Add( apiException.FormatError( ex ) );
         }
      }

      // ----------------------------------------
      private List<campaignEcommOrdersResults> FormatResults( x_campaignEcommOrders[] x_results )
      {
         List<campaignEcommOrdersResults> results = new List<campaignEcommOrdersResults>();
         //
         DateTime dt;
         foreach ( x_campaignEcommOrders result in x_results )
         {
            campaignEcommOrdersResults order = new campaignEcommOrdersResults();
            order.store_id = result.store_id;
            order.store_name = result.store_name;
            order.order_id = result.order_id;
            order.email = result.email;
            order.total = result.order_total;
            order.tax = result.tax_total;
            order.shipping = result.ship_total;
            DateTime.TryParse( result.order_date, out dt );
            order.order_date = dt;
            //
            foreach ( x_campaignEcommOrders_item item in result.lines )
            {
               campaignEcommOrders_item line = new campaignEcommOrders_item();
               line.line_num = item.line_num;
               line.product_id = item.product_id;
               line.product_name = item.product_name;
               line.product_sku = item.product_sku;
               line.category_id = item.product_category_id;
               line.category_name = item.product_category_name;
               line.qty = item.qty;
               line.cost = item.cost;
               order.items.Add( line );
            }
            results.Add( order );
         }
         //
         return results;
      }

      #endregion
   }
}
